package ruifeng.zcj.communcationring.groble;

import android.content.Context;

import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import ruifeng.zcj.communcationring.groble.utils.MD5Util;

/**
 * Created by Administrator on 2016/10/27 0027.
 */
public class WeiXinPay {
    private static IWXAPI api;
    private static String appid = "wx674b7526b05694bb";
    private static String partnerId = "aitxq6@d3jyun.com";//  商户收款账号  商户平台的商户号


    public static void WeiXinPay(Context context,String prepayid
            ,String noncestr,String timestamp,String packages,String sign) {
        api = WXAPIFactory.createWXAPI(context, "wxb4ba3c02aa476ea1");
        // 将该app注册到微信   APP_ID 替换为你的应用从官方网站申请到的合法appId
        api.registerApp("wxb4ba3c02aa476ea1");

        PayReq req = new PayReq();
        req.appId = appid;
        req.partnerId = partnerId;
        req.prepayId = prepayid;//   微信生成的预支付回话标识，用于后续接口调用中使用，该值有效期为2小时
        req.nonceStr = noncestr;//   随机生成一个
        req.timeStamp = timestamp;//
        req.packageValue = "Sign=WXPay";// Sign=WXPay
        req.sign = sign;// 签名，详见签名生成算法
        req.extData = "app data"; // optional
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        api.sendReq(req);
    }




    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(">>>模拟微信支付<<<");
        System.out.println("==========华丽的分隔符==========");
        //微信api提供的参数
        String appid = "wxd930ea5d5a258f4f";
        String mch_id = "10000100";
        String device_info = "1000";
        String body = "test";
        String nonce_str = "ibuaiVcKdpRxkhJA";

        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
        parameters.put("appid", appid);
        parameters.put("mch_id", mch_id);
        parameters.put("device_info", device_info);
        parameters.put("body", body);
        parameters.put("nonce_str", nonce_str);

        String characterEncoding = "UTF-8";
        String weixinApiSign = "9A0A8659F005D6984697E2CA0A9CF3B7";
        System.out.println("微信的签名是：" + weixinApiSign);
        String mySign = createSign(characterEncoding,parameters);
        System.out.println("我     的签名是："+mySign);

        if(weixinApiSign.equals(mySign)){
            System.out.println("恭喜你成功了~");
        }else{
            System.out.println("注定了你是个失败者~");
        }

        String userAgent = "Mozilla/5.0(iphone;CPU iphone OS 5_1_1 like Mac OS X) AppleWebKit/534.46(KHTML,like Geocko) Mobile/9B206 MicroMessenger/5.0";

        char agent = userAgent.charAt(userAgent.indexOf("MicroMessenger")+15);

        System.out.println("微信的版本号："+new String(new char[]{agent}));
    }

    private static String Key = "192006250b4c09247ec02edce69f6a2d";
    /**
     * 微信支付签名算法sign
     * @param characterEncoding
     * @param parameters
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + Key);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }
}
